import { Injectable, NestMiddleware } from '@nestjs/common';
import { decodeToken } from '../util/token';

@Injectable()
export class TokenMiddleware implements NestMiddleware {
  async use(req: any, res: any, next: () => void) {
    const authorization = req.headers['authorization'];
    if (authorization && authorization.startsWith('Bearer ')) {
      try {
        req.user = await decodeToken(authorization); // 挂载到请求对象上
      } catch (err) {
        req.user = null; // token无效也继续执行，让后续层决定是否拒绝
      }
    } else {
      req.user = null;
    }
    next();
  }
}
